﻿using System;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;

namespace AopDemo
{
    #region 动态代理

    public class MyRealProxy<T> : RealProxy
    {
        private T _target;

        public MyRealProxy(T target) : base(typeof(T))
        {
            this._target = target;
        }
        public override IMessage Invoke(IMessage msg)
        {
            PreProceede(msg);
            IMethodCallMessage callMessage = (IMethodCallMessage)msg;
            object returnValue = callMessage.MethodBase.Invoke(this._target, callMessage.Args);
            PostProceede(msg);
            return new ReturnMessage(returnValue, new object[0], 0, null, callMessage);
        }
        public void PreProceede(IMessage msg)
        {
            Console.WriteLine("方法执行前");
        }
        public void PostProceede(IMessage msg)
        {
            Console.WriteLine("方法执行后");
        }

    }
    public static class TransparentProxy
    {
        public static T Create<T>()
        {
            T instance = Activator.CreateInstance<T>();
            MyRealProxy<T> realProxy = new MyRealProxy<T>(instance);
            return (T)realProxy.GetTransparentProxy();
        }
    }
    public interface IUserProcessorByDynamicProxy
    {
        void RegUser(User user);
    }

    public class UserProcessorByDynamicProxy : MarshalByRefObject, IUserProcessorByDynamicProxy
    {
        public void RegUser(User user)
        {
            Console.WriteLine("DynamicProxyClient 用户已注册。");
        }
    }
    public class DynamicProxyClient
    {
        public static void Run()
        {
            try
            {
                User user = new User() { Name = "lee", PassWord = "123123123123" };
                UserProcessorByDynamicProxy userprocessor = TransparentProxy.Create<UserProcessorByDynamicProxy>();
                userprocessor.RegUser(user);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

    #endregion
}
